package com.uspacex.calculate.controller;

import com.alibaba.fastjson.JSONObject;
import com.uspacex.calculate.entity.AnalysisTaskInfo;
import com.uspacex.calculate.mapper.AnalysisTaskMapper;
import com.uspacex.calculate.mapper.MySQLToolsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.uspacex.calculate.service.createSubjectTable;
import java.util.*;

@Controller
@RequestMapping("/analysis")
public class AnalysisTaskController {

    @Autowired
    AnalysisTaskMapper analysisTaskMapper;

    @Autowired
    MySQLToolsMapper mySQLToolsMapper;

    @RequestMapping(value = "/task/tasks", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    List<AnalysisTaskInfo> getAllTasks() {
        return analysisTaskMapper.getAllTasks();
    }

    @RequestMapping(value = "/task/create", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> createATask(@RequestBody AnalysisTaskInfo newTask) {
        String uuid = UUID.randomUUID().toString();
        Map<String, Object> map = new HashMap<>();

        newTask.setTaskId(uuid);
        newTask.setCreateTime(new Date(System.currentTimeMillis()));
        analysisTaskMapper.createATask(newTask);

        map.put("taskId", uuid);
        return map;
    }


    @RequestMapping(value = "/task/delete/{taskId}", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> deleteATask(@PathVariable("taskId") String taskId) {
        Map<String, Object> map = new HashMap<>();
        AnalysisTaskInfo task = analysisTaskMapper.getATask(taskId);

        if (task == null) {
            return map;
        } else {
            if (task.getDatasets() != null) {
                String [] datasets = task.getDatasets().split(";");
                analysisTaskMapper.deleteTask(taskId);
                // 删除任务时，删除该任务在数据集步骤中复制的表
                for (String dataset : datasets) {
                    mySQLToolsMapper.dropTable("data_analysis_db", dataset);
                }
            } else {
                analysisTaskMapper.deleteTask(taskId);
            }
        }

        return map;
    }


    @RequestMapping(value = "/dataset/dbs", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    Map<String, Object> getAllSubjectDBs() {
        Map<String, Object> map = new HashMap<>();
        map.put("subjectDBs", analysisTaskMapper.getAllSubjectDBs());
        return map;
    }


    @RequestMapping(value = "/dataset/config", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> submitDatasetConfig(@RequestBody String str) throws Exception {
        Map<String, Object> resquestParams = JSONObject.parseObject(str, Map.class);
        Map<String, Object> map = new HashMap<>();
        String taskId = (String) resquestParams.get("taskId");
        AnalysisTaskInfo task = analysisTaskMapper.getATask(taskId);
        if (task == null) {
            map.put("message", "尚未创建该任务！, taskId：" + taskId + "。");
            return map;
        }

        List<Map<String, String>> selectTables = (List<Map<String,String>>) resquestParams.get("datasets");

        StringBuilder datasets = new StringBuilder();

        for (Map<String, String> item : selectTables) {
            String sourceDB = item.get("dbName");
            String sourceTB = item.get("tableName");
            String comment = item.get("dbComment") + ": " + item.get("tableComment") + "(" + sourceDB + "." + sourceTB + ")";
            String targetDB = "data_analysis_db";
            String targetTB = sourceTB+"_"+ task.getId() + "_" + UUID.randomUUID().toString().replaceAll("-", "").substring(0,5);
            mySQLToolsMapper.copyTable(sourceDB, sourceTB, targetDB, targetTB);
            mySQLToolsMapper.modifyComment(targetDB, targetTB, comment);
            createSubjectTable cs =new createSubjectTable();
            cs.alterKey(targetTB,targetDB);
            datasets.append(targetTB).append(";");
        }

        analysisTaskMapper.setDataset(datasets.toString(), taskId);

        return map;
    }



}
